package com.derbysoft.dswitch.adapter.ihg.common.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.*;

/**
 * User: jason
 * Date: 12-5-2
 */
public abstract class ExecutorUtils {

    public static <T> List<T> batchExecute(Collection<Callable<T>> tasks,Executor executor) throws ExecutionException, InterruptedException {
        Collection<Future<T>> futures = submitTasks(tasks,executor);
        List<T> results = new ArrayList<T>(tasks.size());
        for (Future<T> future : futures) {
            results.add(future.get());
        }
        return results;
    }

    private static <T> List<Future<T>> submitTasks(Collection<Callable<T>> tasks,Executor executor) {
        CompletionService<T> service = new ExecutorCompletionService<T>(executor);
        List<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
        for (Callable<T> task : tasks) {
            futures.add(service.submit(task));
        }
        return futures;
    }
}
